package com.ljs.module.util;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljs.module.common.PathEnum;
import com.ljs.module.entity.api.ApiEntity;
import com.ljs.module.entity.api.ApiEntityDto;
import com.ljs.module.entity.smartbi.XmlBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.queryparser.classic.ParseException;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created by lijunsai on 2021/09/18
 */
public class ApiUtil {

    static String javaApiPath = PathEnum.API.getPath() + File.separator + "java" + File.separator;
    static String jsApiPath = PathEnum.API.getPath() + File.separator + "js" + File.separator;
    static Map<String, Boolean> ignoreMethod = new HashMap<>();
    public static List<ApiEntity> javaEntities = new ArrayList<>();
    public static List<ApiEntity> jsEntities = new ArrayList<>();
    public static List<ApiEntityDto> allEntities = new ArrayList<>();
    static Integer row = 5;
    public static Integer column = 2;

    static IKAnalyzer ikAnalyzer = new IKAnalyzer(true);

    static {
        ignoreMethod.put("wait", true);
        ignoreMethod.put("equals", true);
        ignoreMethod.put("toString", true);
        ignoreMethod.put("hashCode", true);
        ignoreMethod.put("getClass", true);
        ignoreMethod.put("notify", true);
        ignoreMethod.put("notifyAll", true);
        ignoreMethod.put("getInstance", true);
        ignoreMethod.put("activate", true);
        ignoreMethod.put("setDaoModule", true);
        ignoreMethod.put("getDaoModule", true);
        init();
        mergeAll();
    }

    public static List<ApiEntityDto> page(List<ApiEntityDto> list, Integer page){
        Integer pageSize = row * column;
        List<ApiEntityDto> ret = new ArrayList<>();
        for (int i = pageSize * (page - 1); i < list.size() && i < pageSize * (page - 1) + pageSize; i++) {
            ret.add(list.get(i));
        }
        return ret;
    }

    public static void mergeAll() {
        allEntities.clear();
        allEntities.addAll(transApiEntities2Dto(javaEntities));
        allEntities.addAll(transApiEntities2Dto(jsEntities));
    }

    public static List<ApiEntityDto> transApiEntities2Dto(List<ApiEntity> entities) {
        return entities.stream().map(x ->
                x.transDto().setScore(new Double(0)).setKeyWords(x.getKeyword().split(" ")))
                .collect(Collectors.toList());
    }

    public static void init(){
        File file = new File(javaApiPath + "api.txt");
        if (file.exists() && javaEntities.size() == 0) {
            String content = FileUtil.readFile2Content(javaApiPath + "api.txt");
            javaEntities.addAll(JSONArray.parseArray(content, ApiEntity.class));
        }
        file = new File(jsApiPath + "api.txt");
        if (file.exists() && jsEntities.size() == 0) {
            String content = FileUtil.readFile2Content(jsApiPath + "api.txt");
            jsEntities.addAll(JSONArray.parseArray(content, ApiEntity.class));
        }
    }

    public static void refreshJavaApi(String path, Integer type) {
        try {
            if (type == null) {
                jsEntities = JsAPIUtil.searchAllApi(path);
                javaEntities = JavaAPIUtil.searchAllApi(path);
            }
            if (type == 1) {
                javaEntities = JavaAPIUtil.searchAllApi(path);
            } else if (type == 0){
                jsEntities = JsAPIUtil.searchAllApi(path);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static String findLightStr(String light) {
        Boolean next = false;
        LinkedList list = new LinkedList();
        String temp = "";
        for (String s : light.split("")) {
            if (s.equals("{") && !next) {
                next = true;
                temp += "<span style='color:red;'>";
                continue;
            } else if (s.equals("}") && next) {
                if (list.size() == 0) {
                    next = false;
                    temp += "</span>";
                } else {
                    list.removeFirst();
                }
                continue;
            }
            if (s.equals("{") && next) {
                list.addFirst("{");
                continue;
            }
            temp += s;
        }
        return temp;
    }

    public static void search(ApiEntity apiEntity, String word, Set<ApiEntityDto> sortedSet) {
        init();
        ApiEntityDto dto = apiEntity.transDto();
        String keyword = apiEntity.getKeyword();
        String[] keywords = keyword.split(" ");
        // 对搜索词进行分词
        List<String> analyseResult = getAnalyseResult(word);
        // 匹配关键词
        for (int i = 0; i < keywords.length; i++) {
            String s = keywords[i];
            for (String search : analyseResult) {
                // 匹配时计算匹配分数
                if (s.toLowerCase().contains(search)) {
                    BigDecimal bigDecimal = new BigDecimal(s.length());
                    BigDecimal bigDecimal1 = new BigDecimal(search.length());
                    BigDecimal divide = bigDecimal1.divide(bigDecimal, 2, BigDecimal.ROUND_HALF_UP);
                    if (dto.getScore() != null) {
                        dto.setScore(divide.add(new BigDecimal(dto.getScore()), new MathContext(2)).doubleValue());
                    } else {
                        dto.setScore(divide.doubleValue());
                    }
                    dto.getLight().add(search);
                }
            }
        }
        if (dto.getScore() != null) {
            // 设置高亮 存储索引位可以解决匹配不上的问题，不需要额外排序
//            List<String> collect = dto.getLight().stream().sorted(Comparator.comparing(String::length).reversed()).collect(Collectors.toList());
            for (int i = 0; i < keywords.length; i++) {
                String[] insert = null;
                // 匹配最后一个的时候  索引会越界，记录是否是最后一个
                boolean hasEnd = false;
                for (String light : dto.getLight()) {
                    if (keywords[i].toLowerCase().contains(light) && (!light.contains("{") || !light.contains("}"))) {
                        if (insert == null) {
                            insert = new String[keywords[i].length()];
                        }
                        Pattern p = Pattern.compile(light, Pattern.CASE_INSENSITIVE);
                        Matcher m = p.matcher(keywords[i]);
                        while(m.find()){
                            // 记录需要高亮的索引位
                            if (StringUtils.isBlank(insert[m.start()])) {
                                insert[m.start()] = "";
                            }
                            int end = m.end();
                            if (m.end() == insert.length) {
                                hasEnd = true;
                                end = m.end() - 1;
                            }
                            if (StringUtils.isBlank(insert[end])) {
                                insert[end] = "";
                            }
                            insert[m.start()] += "{";
                            insert[end] += "}";
//                            keywords[i] = keywords[i].replaceAll(m.group(), "{" + m.group() + "}");
                        }
                    }
                }
                if (insert != null) {
                    String temp = "";
                    // 将高亮范围根据索引写入temp中(可以解决并集的问题)
                    String[] split = keywords[i].split("");
                    for (int i1 = 0; i1 < split.length; i1++) {
                        if (!StringUtils.isBlank(insert[i1])) {
                            if (i1 == split.length - 1 && hasEnd) {
                                temp += split[i1] + insert[i1];
                                break;
                            }
                            temp += insert[i1];
                        }
                        temp += split[i1];
                    }
                    // 设置高亮样式
                    keywords[i] = findLightStr(temp);
                }
            }
            dto.setKeyWords(keywords);
            sortedSet.add(dto);
        }
    }

    public static List<ApiEntityDto> search(String word, Integer type) {
        init();
        Set<ApiEntityDto> sortedSet = new TreeSet<>(Comparator.comparing(ApiEntityDto::getScore).reversed());
        if (type == null || type == 1) {
            for (ApiEntity javaEntity : javaEntities) {
                search(javaEntity, word, sortedSet);
            }
        }

        if (type == null || type == 0) {
            for (ApiEntity jsEntity : jsEntities) {
                search(jsEntity, word, sortedSet);
            }
        }
        return sortedSet.stream().collect(Collectors.toList());
    }

    public static List<ApiEntityDto> getMethod(String path, Integer type) {
        init();
        String basePath = type == 1 ? javaApiPath : jsApiPath;
        String fileName = path.substring(path.lastIndexOf(".") + 1);
        String filePath = basePath + path.replaceAll("\\.", Util.getNowFileSepartor()) + File.separator + fileName + ".txt";
        String content = FileUtil.readFile2Content(filePath);
        return transApiEntities2Dto(JSONArray.parseArray(content, ApiEntity.class));
    }

    public static List<String> getAnalyseResult(String analyzeStr) {
        List<String> response = new ArrayList<String>();
        TokenStream tokenStream = null;
        try {
            tokenStream = ikAnalyzer.tokenStream("content", new StringReader(analyzeStr));
            CharTermAttribute attr = tokenStream.addAttribute(CharTermAttribute.class);
            tokenStream.reset();
            while (tokenStream.incrementToken()) {
                response.add(attr.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (tokenStream != null) {
                try {
                    tokenStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

    public static void main(String[] args) throws DocumentException, IOException, ParseException {
//        List<String> ls = ftp.ls("/22.项目扩展包/");
//        System.out.println(ls);

//        String str="Hello world,hello java";
//
//        System.out.println("===========区分大小写===========");
//        Pattern p= Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
//        Matcher m=p.matcher(str);
//        while(m.find()){
//            System.out.println(m.group()+" 位置：["+m.start()+","+m.end()+"]");
//        }
//        String path = "D:\\program data\\version\\smartbi\\v72\\smartbi\\WEB-INF\\web.xml";
//        Document document = new SAXReader().read(new File(path));
//        Element rootElement = document.getRootElement();
//        List<Element> beans = rootElement.elements("context-param");
//        for (Element bean : beans) {
//            String text = bean.element("param-name").getText();
//            if ("DevEnv".equals(text)) {
//                String value = bean.element("param-value").getText();
//                if ("true".equals(value)) {
//                    System.out.println(1);
//                }
//            }
//        }
//        List<String> test = getAnalyseResult("测试中文service");
//        System.out.println(test);
//        List<ApiEntityDto> method = ApiUtil.getMethod("smartbi.freequery.client.portal.PortalService");
//        System.out.println(1);
//        JsAPIUtil.searchAllApi("C:\\Users\\admin\\Desktop\\runtime\\v97\\smartbi");
//        Class<?>[] interfaces = ApiUtil.class.getInterfaces();
//        for (Class<?> anInterface : interfaces) {
//            System.out.println(anInterface.getSimpleName());
//        }
//        String word = "dao";
//        SortedSet<ApiEntityDto> sortedSet = new TreeSet<>(Comparator.comparing(ApiEntityDto::getScore));
//        for (ApiEntity javaEntity : javaEntities) {
//            ApiEntityDto dto = javaEntity.transDto();
//            String keyword = javaEntity.getKeyword();
//            for (String s : keyword.split(" ")) {
//                if (s.toLowerCase().contains(word)) {
//                    BigDecimal bigDecimal = new BigDecimal(s.length());
//                    BigDecimal bigDecimal1 = new BigDecimal(word.length());
//                    double now = bigDecimal1.divide(bigDecimal, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
//                    if (dto.getScore() != null) {
//                        if (now > dto.getScore()) {
//                            dto.setScore(now);
//                        }
//                    } else {
//                        dto.setScore(now);
//                    }
//                    dto.setLight((StringUtils.isBlank(dto.getLight())) ? word : (dto.getLight() + " " + word));
//                }
//            }
//            if (dto.getScore() != null) {
//                sortedSet.add(dto);
//            }
//        }
//        System.out.println(sortedSet);
//        String str = "中文测试吃饭";
//        System.out.println(ToAnalysis.parse(str));
    }



    static class JavaAPIUtil {

        public static Map<String, XmlBean> loadApplicationXmlBeans(String path) throws DocumentException {
            Document document = new SAXReader().read(new File(path));
            Element rootElement = document.getRootElement();
            List<Element> beans = rootElement.elements("bean");
            Map<String, XmlBean> packages = new HashMap<>();

            for (Element bean : beans) {
                String id = bean.attribute("id").getText();
                String packageName = bean.attribute("class").getText();
                XmlBean xmlBean = new XmlBean()
                        .setId(id)
                        .setPackageName(packageName);
                List<Element> propertys = bean.elements("property");
                for (Element property : propertys) {
                    Attribute ref = property.attribute("ref");
                    if (ref != null) {
                        xmlBean.getBeanNames().add(property.attribute("name").getValue());
                        xmlBean.getBeanRefs().add(property.attribute("ref").getValue());
                    } else {
                        Element map = property.element("map");
                        if (map != null) {
                            List<Element> entrys = map.elements("entry");
                            xmlBean.getBeanNames().addAll(entrys.stream().map(x -> x.element("ref").attribute("bean").getText()).collect(Collectors.toList()));
                            xmlBean.getBeanRefs().addAll(entrys.stream().map(x -> x.element("key").element("value").getText()).collect(Collectors.toList()));
                        }
                    }
                }
                packages.put(id, xmlBean);
            }

            String[] beanIds = new String[]{"rmi", "framework"};
            for (String s : beanIds) {
                XmlBean xmlBean = packages.get(s);
                List<String> beanRefs = xmlBean.getBeanRefs();
                for (String beanRef : beanRefs) {
                    XmlBean xmlBeanChild = packages.get(beanRef);
                    if (xmlBeanChild != null) {
                        Map<String, XmlBean> beans1 = xmlBean.getBeans();
                        if (beans1 == null) {
                            beans1 = new HashMap<>();
                            xmlBean.setBeans(beans1);
                        }
                        beans1.put(beanRef, xmlBeanChild);
                    }
                }
            }
            return packages;
        }

        public static String getGeneric (ParameterizedType genericType) {
            Type[] actualTypeArguments = genericType.getActualTypeArguments();
            String str = "<";
            for (int i = 0; i < actualTypeArguments.length; i++) {
                String typeName = actualTypeArguments[i].getTypeName();
                str += typeName.substring(typeName.lastIndexOf(".") + 1) + ((i == actualTypeArguments.length - 1) ? "" : ",");
            }
            return str +=  ">";
        }

        public static String getMethodFullString(Method method) {
            String s1 = "";
            // 判断修饰符
            switch (method.getModifiers()) {
                case 1:  s1 += "public "; break;
                case 2:  s1 += "private "; break;
                case 4:  s1 += "protected "; break;
                case 8:  s1 += "static "; break;
                case 16:  s1 += "final "; break;
            }
            // 返回类型
            Type genericReturnType = method.getGenericReturnType();
            s1 += method.getReturnType().getSimpleName();
            // 返回类型是否有泛型
            if (genericReturnType instanceof ParameterizedType) {
                s1 += getGeneric((ParameterizedType) genericReturnType);
            }
            s1 += " " + method.getName() + " (";
            Type[] genericParameterTypes = method.getGenericParameterTypes();
            // 参数
            Parameter[] parameters = method.getParameters();
            // 参数是否有泛型
            for (int i = 0; i < genericParameterTypes.length; i++) {
                s1 += parameters[i].getType().getSimpleName();
                if (genericParameterTypes[i] instanceof ParameterizedType) {
                    s1 += getGeneric((ParameterizedType) genericParameterTypes[i]);
                } else {
                    s1 += ((i == genericParameterTypes.length - 1) ? "" : ",");
                }
            }
            s1 += ")";
            return s1;
        }

        public static String getExtendsOrInterface(Class clazz) {
            String father = "";
            Class superclass = clazz.getSuperclass();
            if (superclass != Object.class) {
                father += "extends " + superclass.getSimpleName();
            }

            Class[] interfaces = clazz.getInterfaces();

            if (interfaces != null && interfaces.length > 0) {
                father += " implements ";
                for (Class anInterface : interfaces) {
                    father += anInterface.getSimpleName() + ",";
                }
                father = father.substring(0, father.length() - 1);
            }
            return father;
        }

        public static List<ApiEntity> searchAllApi(String path) throws DocumentException {
            // 加载smartbi下 applicationContext.xml 暴露的类
            Map<String, XmlBean> packages = loadApplicationXmlBeans(path + File.separator + "WEB-INF" + File.separator +"applicationContext.xml");

            MyWebAppLoader myWebAppLoader = null;
            ObjectMapper objectMapper = new ObjectMapper();
            List<ApiEntity> entitiesAll = new ArrayList<>();
            try {
                // 加载smartbi下 SDK中的所有的类
                myWebAppLoader = new MyWebAppLoader(path + File.separator + "WEB-INF" + File.separator + "lib");
                Map<String, byte[]> map = myWebAppLoader.map;
                Set<String> keySet1 = packages.keySet();
                for (String s : keySet1) {
                    try {
                        Class<?> myclass = myWebAppLoader.loadClass(packages.get(s).getPackageName());
                        String classFullName = myclass.getName().replaceAll("\\.",File.separator);
                        String className = classFullName.substring(classFullName.lastIndexOf(File.separator) + 1);
                        String fileName = className + ".txt";
                        final String classPath = classFullName;
                        String trueApiPath = javaApiPath + classFullName;
                        FileUtil.directoryNotExistThenMake(trueApiPath);
                        FileUtil.fileNotExistThenMake(trueApiPath + File.separator + fileName);
                        ApiEntity apiEntity = new ApiEntity()
                                .setType(1).setKeyword(packages.get(s).getId() + " " + className).setDesc(className)
                                .setIsDelete(0).setName(className).setVersion("0").setFather(getExtendsOrInterface(myclass))
                                .setUpdateTime(new Date()).setPath(classFullName.replaceAll(File.separator, "."));
                        entitiesAll.add(apiEntity);

                        // 解析所有方法
                        Method[] methods = myclass.getMethods();
                        List<ApiEntity> collect = Arrays.stream(methods)
                                .filter(x -> {
                                    Boolean aBoolean = ignoreMethod.get(x.getName());
                                    if (aBoolean != null) {
                                        return !aBoolean;
                                    }
                                    return true;
                                })
                                .map(x -> new ApiEntity().setType(1).setKeyword(x.getName()).setDesc(x.getName())
                                            .setName(getMethodFullString(x)).setVersion("0").setPath(classPath)
                                            .setUpdateTime(new Date()).setIsDelete(0)
                                ).collect(Collectors.toList());

                        // 写入具体文件中
                        String content = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(collect);
                        FileUtil.writeContent2File(trueApiPath + File.separator + fileName, content);
                        System.out.println(myclass.getName());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
                // 写入总api文档中
                String content = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(entitiesAll);
                String filePath = javaApiPath + "api.txt";
                FileUtil.fileNotExistThenMake(filePath);
                FileUtil.writeContent2File(filePath,content);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (myWebAppLoader != null) {
                    myWebAppLoader.map.clear();
                }
            }
            return entitiesAll;
        }
    }

    static class JsAPIUtil {
        public static List<ApiEntity> searchAllApi(String path) {
            String filePath = path + File.separator + "vision" + File.separator +"js";
            File file = new File(filePath);
            List<File> files = new ArrayList<>();
            List<ApiEntity> list = new ArrayList<>();
            getAllJsFile(files, file);
            ObjectMapper objectMapper = new ObjectMapper();
            for (File file1 : files) {
                String absolutePath = file1.getAbsolutePath();
                String entityPath = absolutePath.substring(absolutePath.indexOf(filePath) + filePath.length() + 1, absolutePath.lastIndexOf("."))
                        .replaceAll(File.separator, ".");
                if (saveFunction(file1, entityPath)) {
                    String name = file1.getName().substring(0, file1.getName().lastIndexOf("."));
                    ApiEntity apiEntity = new ApiEntity()
                            .setType(0).setKeyword(name).setDesc(name)
                            .setIsDelete(0).setName(name).setVersion("0").setFather("")
                            .setUpdateTime(new Date()).setPath(entityPath);
                    list.add(apiEntity);
                }
            }
            // 写入总api文档中
            try {
                String content = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
                FileUtil.directoryNotExistThenMake(jsApiPath);
                FileUtil.fileNotExistThenMake(jsApiPath + File.separator +"api" + ".txt");
                // 写入总api文档中
                FileUtil.writeContent2File(jsApiPath + File.separator +"api" + ".txt", content);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return list;
        }

        public static void getAllJsFile(List<File> files, File file) {
            File[] files1 = file.listFiles(x -> x.getName().endsWith(".js"));
            if (files1 != null && files1.length > 0) {
                files.addAll(Arrays.asList(files1));
            }
            File[] files2 = file.listFiles(x -> x.isDirectory() && !x.getName().equals("thirdparty"));
            if (files2 != null && files2.length > 0) {
                for (File file1 : files2) {
                    getAllJsFile(files, file1);
                }
            }
        }

        public static String removeSomeWord(String temp) {
            temp = temp.replaceAll(" ", "").replaceAll("\t", "");
            if (temp.contains("\\\\")) {
                temp = temp.substring(0, temp.indexOf("\\\\"));
            }
            return temp;
        }

        public static ApiEntity createApiEntity(String tempString, String entityPath, String name){
            ApiEntity apiEntity = new ApiEntity()
                    .setType(0).setIsDelete(0).setVersion("0").setFather("")
                    .setUpdateTime(new Date()).setPath(entityPath);
            apiEntity.setKeyword(name).setDesc(name).setName(tempString.replaceAll("[{}]", ""));
            return apiEntity;
        }

        public static List<ApiEntity> findPrototype(File file, String entityPath) {
            BufferedReader reader = null;
            List<ApiEntity> apiEntities = new ArrayList<>();
            try {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String temp = "";
                String tempString = "";
                while ((temp = reader.readLine()) != null) {
                    temp = removeSomeWord(temp);
                    if (temp.indexOf(file.getName().substring(0, file.getName().indexOf("."))) == 0 && temp.contains(".prototype")) {
                        tempString += temp;
                        if (!temp.contains("{")) {
                            while ((temp = reader.readLine()) != null) {
                                tempString += temp;
                                if (temp.contains("{")){
                                    tempString += "}";
                                    String name = tempString.substring(tempString.lastIndexOf(".") + 1, tempString.indexOf("="));
                                    apiEntities.add(createApiEntity(tempString, entityPath, name));
                                    tempString = "";
                                    break;
                                }
                            }
                        } else {
                            tempString += "}";
                            String name = tempString.substring(tempString.lastIndexOf(".") + 1, tempString.indexOf("="));
                            apiEntities.add(createApiEntity(tempString, entityPath, name));
                            tempString = "";
                        }
                    }
                }
                return apiEntities;
            } catch (Exception e) {
                return null;
            }
        }

        public static List<ApiEntity> findObjectFunction(File file, String entityPath) {
            List<ApiEntity> apiEntities = new ArrayList<>();

            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String temp = "";
                String tempString = "";
                while ((temp = reader.readLine()) != null) {
                    temp = removeSomeWord(temp);
                    if (temp.replaceAll(" ", "").contains(":function")) {
                        tempString += temp;
                        if (!temp.contains("{")) {
                            while ((temp = reader.readLine()) != null) {
                                tempString += temp;
                                if (temp.contains("{")){
                                    tempString += "}";
                                    String name = tempString.substring(0, tempString.indexOf(":"));
                                    apiEntities.add(createApiEntity(tempString, entityPath, name));
                                    tempString = "";
                                    break;
                                }
                            }
                        } else {
                            tempString += "}";
                            String name = tempString.substring(0, tempString.indexOf(":"));
                            apiEntities.add(createApiEntity(tempString, entityPath, name));
                            tempString = "";
                        }
                    }
                }
                return apiEntities;
            } catch (Exception e) {
                return null;
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


        public static boolean saveFunction(File file, String entityPath) {
            ObjectMapper objectMapper = new ObjectMapper();
            List<ApiEntity> entities = new ArrayList<>();
            try {
                entities = findPrototype(file, entityPath);
                if (entities == null || entities.size() == 0) {
                    System.err.println(file.getAbsolutePath() + "     -----读取原型失败，开始读取对象方法");
                    entities = findObjectFunction(file, entityPath);
                }

            } catch (Exception e) {
                System.err.println("-------------" + file.getAbsolutePath() + "读取失败");
                return false;
            }

            try {
                if (entities == null || entities.size() == 0) {
                    System.err.println(file.getAbsolutePath() + "     -----没有方法");
                    return false;
                }
                String name = file.getName();
                name = name.substring(0, name.lastIndexOf("."));
                String absolutePath = file.getAbsolutePath();
                absolutePath = absolutePath.substring(absolutePath.indexOf(File.separator + "smartbi" + File.separator + "vision" + File.separator + "js") + (File.separator + "smartbi" + File.separator + "vision" + File.separator + "js").length(), absolutePath.lastIndexOf(Util.getNowFileSepartor()));
                FileUtil.directoryNotExistThenMake(jsApiPath  + absolutePath + File.separator + name + File.separator);
                FileUtil.fileNotExistThenMake(jsApiPath + absolutePath + File.separator + name + File.separator + name + ".txt");
                // 写入总api文档中
                String content = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(entities);
                FileUtil.writeContent2File(jsApiPath + absolutePath + File.separator + name + File.separator + name + ".txt", content);
            } catch (Exception e) {
                System.err.println("------------------解析js失败:" + file.getAbsolutePath());
                return false;
            }
            return true;
        }
    }
}
